package com.mdd.admin.service.staff.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.map.model.MapLocation;
import com.google.common.collect.Lists;
import com.mdd.admin.service.goods.IGoodsService;
import com.mdd.admin.service.order.IOrderService;
import com.mdd.admin.service.region.IDevRegionService;
import com.mdd.admin.service.staff.IStaffService;
import com.mdd.admin.service.user.IUserService;
import com.mdd.admin.validate.staff.StaffParam;
import com.mdd.admin.validate.staff.StaffStatusParam;
import com.mdd.admin.vo.goods.GoodsDetailVo;
import com.mdd.admin.vo.staff.StaffDetailVo;
import com.mdd.admin.vo.staff.StaffListVo;
import com.mdd.admin.vo.staff.StaffPageParam;
import com.mdd.common.config.map.LikeTenCentClient;
import com.mdd.common.constant.GlobalConstant;
import com.mdd.common.core.PageResult;
import com.mdd.common.dto.StaffDto;
import com.mdd.common.dto.result.StaffResultDto;
import com.mdd.common.entity.staff.Staff;
import com.mdd.common.enums.RecommendEnum;
import com.mdd.common.enums.StatusEnum;
import com.mdd.common.exception.OperateException;
import com.mdd.common.mapper.staff.StaffMapper;
import com.mdd.common.utils.TimeUtil;
import com.mdd.common.utils.UrlUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 师傅实现类
 */
@Service
public class StaffServiceImpl extends ServiceImpl<StaffMapper, Staff> implements IStaffService {

    @Resource
    private StaffMapper staffMapper;

    @Resource
    private IDevRegionService regionService;

    @Resource
    private IUserService userService;

    @Resource
    private IGoodsService goodsService;

    @Resource
    private IOrderService orderService;

    @Resource
    private LikeTenCentClient mapClient;

    /**
     * 师傅列表
     *
     * @param params 搜索参数
     * @return PageResult<StaffListVo>
     */
    @Override
    public PageResult<StaffListVo> list(StaffPageParam params) {
        Page<StaffListVo> page = new Page<>(params.getPageNo(), params.getPageSize());
        StaffDto pageDto = new StaffDto();
        BeanUtils.copyProperties(params, pageDto);
        Page<StaffResultDto> resultDtoPage = staffMapper.page(page, pageDto);
        if (resultDtoPage == null || CollectionUtils.isEmpty(resultDtoPage.getRecords())) {
            return PageResult.iPageHandle(0L, page.getCurrent(), page.getSize(), Lists.newArrayList());
        }
        List<StaffListVo> list = new LinkedList<>();
        Map<Long, String> regionMap = regionService.getRegionMap();
        Map<Integer, String> recommendMap = RecommendEnum.getMap();
        Map<Integer, String> statusMap = StatusEnum.getMap();
        for (StaffResultDto item : resultDtoPage.getRecords()) {
            StaffListVo vo = new StaffListVo();
            BeanUtils.copyProperties(item, vo);
            vo.setStatusName(statusMap.get(vo.getStatus()));
            vo.setIsRecommendName(recommendMap.get(vo.getIsRecommend()));
            vo.setProvince(regionMap.get(vo.getProvinceId()));
            vo.setCity(regionMap.get(vo.getCityId()));
            vo.setDistrict(regionMap.get(vo.getDistrictId()));
            vo.setAvatarUrl(UrlUtil.toAbsoluteUrl(item.getAvatarUri()));
            vo.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtil.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }
        return PageResult.iPageHandle(resultDtoPage.getTotal(), resultDtoPage.getCurrent(), resultDtoPage.getSize(), list);
    }

    /**
     * 师傅详情
     *
     * @param id 主键参数
     * @return Staff
     */
    @Override
    public StaffDetailVo detail(Long id) {
        Staff model = staffMapper.selectOne(
                new QueryWrapper<Staff>()
                        .eq("id", id)
                        .last("limit 1"));
        Assert.notNull(model, "数据不存在");
        StaffDetailVo vo = new StaffDetailVo();
        BeanUtils.copyProperties(model, vo);
        Map<Long, String> regionMap = regionService.getRegionMap();
        vo.setProvince(regionMap.get(vo.getProvinceId()));
        vo.setCity(regionMap.get(vo.getCityId()));
        vo.setDistrict(regionMap.get(vo.getDistrictId()));
        vo.setStatusName(StatusEnum.getMap().get(vo.getStatus()));
        vo.setIsRecommendName(RecommendEnum.getMap().get(vo.getIsRecommend()));
        vo.setUserVo(userService.detail(model.getUserId().intValue()));
        vo.setCreateTime(TimeUtil.timestampToDate(model.getCreateTime()));
        vo.setUpdateTime(TimeUtil.timestampToDate(model.getUpdateTime()));
        List<Long> goodsIds = Lists.newArrayList();
        List<String> goodsIdsStr = Arrays.asList(StringUtils.split(model.getGoodsIds(), ","));
        CollectionUtils.collect(goodsIdsStr, input -> Long.valueOf(input.toString()), goodsIds);
        List<GoodsDetailVo> goodsDetailVoList = goodsService.detailByIds(goodsIds);
        vo.setGoodsList(goodsDetailVoList);
        vo.setLevel(model.getLevel());
        vo.setIsFreelance(model.getIsFreelance());
        return vo;
    }

    /**
     * 师傅新增
     *
     * @param staffParam 参数
     */
    @Override
    public void add(StaffParam staffParam) {
        Staff staff = super.getOne(new QueryWrapper<Staff>()
                .select("id,sn,name")
                .nested(
                        wq -> wq.eq("user_id", staffParam.getUserId())
                )
                .eq("is_delete", 0)
                .last("limit 1"));
        Assert.isNull(staff, "师傅编号重复/一个用户多次绑定师傅");
        MapLocation address = mapClient.address(staffParam.getAddress());
        Staff model = new Staff();
        model.setUserId(staffParam.getUserId());
        model.setSn(staffParam.getSn());
        model.setName(staffParam.getName());
        model.setSex(staffParam.getSex());
        model.setMobile(staffParam.getMobile());
        model.setGoodsIds(staffParam.getGoodsIds());
        model.setProvinceId(staffParam.getProvinceId());
        model.setCityId(staffParam.getCityId());
        model.setDistrictId(staffParam.getDistrictId());
        model.setAddress(staffParam.getAddress());
        model.setLongitude(ObjectUtils.isNotEmpty(address) ? StringUtils.defaultString(address.getLng(), staffParam.getLongitude()) : staffParam.getLongitude());
        model.setLatitude(ObjectUtils.isNotEmpty(address) ? StringUtils.defaultString(address.getLat(), staffParam.getLatitude()) : staffParam.getLatitude());
        model.setStatus(staffParam.getStatus());
        model.setIsRecommend(staffParam.getIsRecommend());
        model.setCreateTime(TimeUtil.timestamp());
        model.setUpdateTime(TimeUtil.timestamp());
        model.setIsFreelance(staffParam.getIsFreelance());
        model.setLevel(staffParam.getLevel());
        model.setType(staffParam.getType());
        staffMapper.insert(model);
    }

    /**
     * 师傅编辑
     *
     * @param staffParam 参数
     */
    @Override
    public void edit(StaffParam staffParam) {
        Staff model = staffMapper.selectOne(
                new QueryWrapper<Staff>()
                        .eq("id", staffParam.getId())
                        .last("limit 1"));
        Assert.notNull(model, "数据不存在!");
//        if(!model.getAddress().equals(staffParam.getAddress())) {
        MapLocation address = mapClient.address(staffParam.getAddress());
        model.setLongitude(ObjectUtils.isNotEmpty(address) ? StringUtils.defaultString(address.getLng(), staffParam.getLongitude()) : staffParam.getLongitude());
        model.setLatitude(ObjectUtils.isNotEmpty(address) ? StringUtils.defaultString(address.getLat(), staffParam.getLatitude()) : staffParam.getLatitude());
//        }
        // 暂时不用
//        else {
//            model.setLongitude(staffParam.getLongitude());
//            model.setLatitude(staffParam.getLatitude());
//        }
        model.setUserId(staffParam.getUserId());
        model.setSn(staffParam.getSn());
        model.setName(staffParam.getName());
        model.setSex(staffParam.getSex());
        model.setMobile(staffParam.getMobile());
        model.setGoodsIds(staffParam.getGoodsIds());
        model.setProvinceId(staffParam.getProvinceId());
        model.setCityId(staffParam.getCityId());
        model.setDistrictId(staffParam.getDistrictId());
        model.setAddress(staffParam.getAddress());
        model.setStatus(staffParam.getStatus());
        model.setIsRecommend(staffParam.getIsRecommend());
        model.setUpdateTime(TimeUtil.timestamp());
        model.setLevel(staffParam.getLevel());
        model.setIsFreelance(staffParam.getIsFreelance());
        model.setType(staffParam.getType());
        staffMapper.updateById(model);
    }

    /**
     * 师傅删除
     *
     * @param id 主键ID
     */
    @Override
    public void del(Long id) {
        Staff model = staffMapper.selectOne(
                new QueryWrapper<Staff>()
                        .eq("id", id)
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");
        Boolean result = orderService.existOrderByStaffId(model.getId());
        if (result) {
            throw new OperateException("已经指派过的师傅不能进行删除");
        }
        model.setIsDelete(GlobalConstant.DELETE);
        model.setDeleteTime(TimeUtil.timestamp());
        staffMapper.updateById(model);
    }

    @Override
    public void status(StaffStatusParam statusParam) {
        Long id = statusParam.getId();
        Staff staff = super.getById(id);
        Assert.notNull(staff, "数据不存在!");
        staff.setStatus(statusParam.getStatus());
        staff.setUpdateTime(TimeUtil.timestamp());
        super.updateById(staff);
    }

    @Override
    public List<Staff> getByCityId(Long cityId) {
        LambdaQueryWrapper<Staff> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Staff::getCityId, cityId);
        lambdaQueryWrapper.eq(Staff::getStatus, 1);
        lambdaQueryWrapper.eq(Staff::getType, 0);
        lambdaQueryWrapper.eq(Staff::getIsDelete, GlobalConstant.NOT_DELETE);
        lambdaQueryWrapper.orderByDesc(Staff::getCreateTime);
        return super.list(lambdaQueryWrapper);
    }
    @Override
    public  PageResult<StaffListVo> water(StaffPageParam params) {
        Page<StaffListVo> page = new Page<>(params.getPageNo(), params.getPageSize());

        StaffDto staffDto = new StaffDto();
        BeanUtils.copyProperties(params, staffDto);
        Page<StaffResultDto> resultDtoPage = staffMapper.water(page,staffDto);

        if (resultDtoPage == null || CollectionUtils.isEmpty(resultDtoPage.getRecords())) {
            return PageResult.iPageHandle(0L, page.getCurrent(), page.getSize(), Lists.newArrayList());
        }
        List<StaffListVo> list =  new LinkedList<>();
        resultDtoPage.getRecords().forEach(it->{
            StaffListVo staffListVo = new StaffListVo();
            BeanUtils.copyProperties(it, staffListVo);
            list.add(staffListVo);
        });
        return PageResult.iPageHandle(resultDtoPage.getTotal(), resultDtoPage.getCurrent(), resultDtoPage.getSize(), list);
    }
}
